import {getOrderOverview, updateOrderStatus, getScanInfo, cancelOrder, getOrderList} from "../services/api.js";

const state = {
    orders: [], // 存储订单列表
    scanResult: null, // 存储扫描结果
};

const mutations = {
    SET_ORDERS(state, orders) {
        state.orders = orders.map(order => ({
            ...order,
            status: order.status.toUpperCase() // 统一转为大写
        }));
    },
    UPDATE_ORDER_STATUS(state, payload) {
        const order = state.orders.find(o => o.id === payload.orderId);
        if (order) {
            order.status = payload.status.toUpperCase();
        }
    },
    SET_SCAN_RESULT(state, result) {
        state.scanResult = result; // 设置扫描结果
    },
    CANCEL_ORDER(state, orderId) {
        const orderIndex = state.orders.findIndex(order => order.id === orderId);
        if (orderIndex !== -1) {
            state.orders.splice(orderIndex, 1); // 从状态中移除已取消的订单
        }
    },
};

const actions = {
    fetchOrders({commit}, status) {
        return axiosInstance.get('/orders', {
            params: {
                status: status === 'all' ? null : status.toUpperCase()
            }
        }).then(orders => {
            commit('SET_ORDERS', orders);
        });
    },
    updateOrderStatus({commit}, {orderId, status}) {
        updateOrderStatus(orderId, status).then(() => {
            commit('UPDATE_ORDER_STATUS', {orderId, status}); // 更新 Vuex 状态
        }).catch(error => {
            console.error("更新订单状态失败", error);
        });
    },
    getScanInfo({commit}, trackingNumber) {
        getScanInfo(trackingNumber).then(result => {
            commit('SET_SCAN_RESULT', result); // 提交 mutation 更新扫描结果
        }).catch(error => {
            console.error("获取快递信息失败", error);
        });
    },
    cancelOrder({commit}, orderId) {
        cancelOrder(orderId).then(() => {
            commit('CANCEL_ORDER', orderId); // 提交 mutation 更新状态
        }).catch(error => {
            console.error("取消订单失败", error);
        });
    },
};

const getters = {
    allOrders: (state) => state.orders, // 获取所有订单
    scanResult: (state) => state.scanResult, // 获取扫描结果
};

export default {
    state,
    mutations,
    actions,
    getters,
};



